<template>
  <!--倒计时功能-->
  <span class="time-text">{{ timeText }}</span>
</template>
<script setup>
  import { formatTime } from '~/utils/base'
  const props = defineProps({
    examTime: { type: Number, default: 0 }, // 单位秒
    tip: { type: String, default: '结束' } // 单位秒
  })
  const { examTime } = toRefs(props)
  const surplusTime = ref(props.examTime)
  watch(examTime, (newValue) => {
    surplusTime.value = newValue
  })

  const emit = defineEmits(['callback'])
  let timerInterval = null
  const timeText = ref('')
  onMounted(() => {
    // 倒计时
    timerInterval = setInterval(() => {
      if (surplusTime.value > 0) {
        surplusTime.value--
        timeText.value = formatTime(surplusTime.value)
      } else {
        clearInterval(timerInterval)
        timeText.value = props.tip
        emit('callback', '考试时间已到')
      }
    }, 1000)
  })
  onUnmounted(() => {
    if (timerInterval) {
      clearInterval(timerInterval)
    }
  })
</script>
<style lang="scss" scoped>
  .time-text {
    color: red;
  }
</style>
